package com.alinesno.cloud.common.web.login.controller;

import java.io.File;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alinesno.cloud.base.boot.entity.ManagerAccountEntity;
import com.alinesno.cloud.base.boot.service.IManagerAccountService;
import com.alinesno.cloud.common.core.constants.SpringInstanceScope;
import com.alinesno.cloud.common.core.monitor.Server;
import com.alinesno.cloud.common.facade.response.ResponseBean;
import com.alinesno.cloud.common.facade.response.ResponseGenerator;
import com.alinesno.cloud.common.web.base.controller.BaseController;
import com.alinesno.cloud.common.web.login.form.ManagerAccountVo;
import com.alinesno.cloud.common.web.login.session.CurrentAccountSession;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;

/**
 * 控制层
 * 
 * @author WeiXiaoJin
 * @since 2018年11月27日 上午6:41:40
 */
@Controller
@Scope(SpringInstanceScope.PROTOTYPE)
@RequestMapping("dashboard/common/")
public class CommonController extends BaseController {

	private static final Logger log = LoggerFactory.getLogger(CommonController.class);

	private static final int UNIQUE = 0 ; 
	private static final int NUNIQUE = 1 ; 
	
	@Autowired
	private IManagerAccountService managerAccountFeign;

	@GetMapping("/user/avatar")
	public String userAvatar() {
		log.debug("进入用户头像编辑页面");
		return "common/user/avatar";
	}
	
	/**
	 *     更新用户头像
	 * @return
	 */
	@ResponseBody
	@PostMapping("/user/avatar")
	public ResponseBean updateUserAvatar(HttpServletRequest request) {
		String path = request.getParameter("path") ; 
		log.debug("avator path = {}" , path);
		
		if(StringUtils.isNotBlank(path)) {
			
			ManagerAccountEntity currentAccount = CurrentAccountSession.get(request) ;
			managerAccountFeign.updateAvator(path , currentAccount.getId()); 
			
			return ResponseGenerator.okMsg("修改用户头像成功.");
		}
		
		return ResponseGenerator.fail(null) ; 
	}

	/**
	 * 更新用户信息
	 * @return
	 */
	@ResponseBody
	@PostMapping("/user/update")
	public ResponseBean updateUser(@Validated ManagerAccountVo entity) {
	
		String id = entity.getId() ;
		ManagerAccountEntity account = managerAccountFeign.getOne(id) ; 
		BeanUtil.copyProperties(entity, account , CopyOptions.create().setIgnoreNullValue(true));
		
		log.debug("entity:{}" , ToStringBuilder.reflectionToString(entity));
		log.debug("account:{}" , ToStringBuilder.reflectionToString(account));
	
		account.setLastUpdateOperatorId(CurrentAccountSession.get(request).getId());
		account = managerAccountFeign.save(account) ; 
		
		return account!=null ? ResponseGenerator.genSuccessMessage("修改用户信息成功."):ResponseGenerator.genFailMessage("修改用户信息失败.");
	}

	@GetMapping("/user/profile")
	public String userProfile(ModelMap mmap, HttpServletRequest request) {
		log.debug("进入用户编辑页面");

		mmap.put("account", managerAccountFeign.getOne(CurrentAccountSession.get(request).getId()));

		return "common/user/profile";
	}

	@GetMapping("/user/resetPassword")
	public String resetPassword(ModelMap mmap, HttpServletRequest request) {
		log.debug("进入用户编辑页面");

		mmap.put("account", managerAccountFeign.getOne(CurrentAccountSession.get(request).getId()));

		return "common/user/resetPassword";
	}

	@ResponseBody
	@PostMapping("/user/resetPassword")
	public ResponseBean updatePassword(ModelMap mmap, HttpServletRequest request, String newPassword , String oldPassword) {
		log.debug("保存用户新修改的密码:{} , 旧密码:{}", newPassword , oldPassword);
		
		Assert.hasLength(newPassword , "用户新密码不能为空.");
		Assert.hasLength(oldPassword, "用户旧密码不能为空.");	
		Assert.isTrue(!oldPassword.equals(newPassword),"新旧密码不能相同")  ; 

		ManagerAccountEntity user = CurrentAccountSession.get(request);
		boolean b = managerAccountFeign.resetPassword(user.getId() , newPassword , oldPassword) ; 
		
		return b?ResponseGenerator.genSuccessMessage("修改密码成功."):ResponseGenerator.genFailMessage("修改密码失败，旧密码错误");

//		if (AStringUtils.isNotEmpty(newPassword) && AStringUtils.isNotEmpty(oldPassword)) {
//			
//			if(oldPassword.equals(newPassword)) {
//				return ResponseGenerator.genFailMessage("新旧密码不能相同.");
//			}
//			
//			if(b) {
//				return ResponseGenerator.genSuccessResult() ; 
//			}
//		} 
		
	}

	@GetMapping("/monitor/server")
	public String monitorServer(ModelMap mmap) throws Exception {
		log.debug("进入服务监控页面");

		Server server = new Server();
		server.copyTo();
		mmap.put("server", server);

		return "common/monitor/server";
	}
	
	@GetMapping("/download")
	public ResponseEntity<byte[]> download(HttpServletRequest request, String fileName , String delete) throws IOException {

		File file = new File(fileName) ; 
		byte[] body = FileUtils.readFileToByteArray(file) ; 
		
		if(Boolean.parseBoolean(delete)) {
			FileUtils.forceDelete(file);
		}
		
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Disposition", "attchement;filename=" + fileName) ;
		HttpStatus statusCode = HttpStatus.OK;
		ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
		return entity;
	}

	/**
	 * 判断邮箱是否唯一
	 * @param request
	 * @return
	 */
	@ResponseBody
	@PostMapping("/user/checkEmailUnique")
	public int checkEmailUnique(HttpServletRequest request , String email , String userId) {
		log.debug("userId = {} , email = {}" , userId , email);
		
		boolean b = managerAccountFeign.checkEmailUnique(email , userId);
		
		return b? UNIQUE : NUNIQUE ; 
	}

	/**
	 * 判断手机号是否唯一
	 * @param request
	 * @param email
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@PostMapping("/user/checkPhoneUnique")
	public int checkPhoneUnique(HttpServletRequest request , String phone, String userId) {
		log.debug("userId = {} , phone = {}" , userId , phone);
		
		boolean b = managerAccountFeign.checkPhoneUnique(phone , userId);
		
		return b? UNIQUE : NUNIQUE ; 
	}
	
	/**
	 * 判断旧密码是否正确 
	 * @param request
	 * @param email
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@GetMapping("/user/checkPassword")
	public boolean checkPassword(HttpServletRequest request , String password , String userId) {
		log.debug("userId = {} , oldPassword = {}" , userId , password);

		ManagerAccountEntity opt = managerAccountFeign.findEntityById(userId) ; 
		if(opt != null && opt.getPassword().equals(password)) {
			return true ; 
		}
		
		return false ; 
	}
}
